package leetcode_1_200;

import java.util.Arrays;

public class LeeCode_179 {
    public static void main(String[] args) {
        System.out.println(largestNumber(new int[]{10, 2}));
        System.out.println(largestNumber(new int[]{3, 30, 34, 5, 9}));
        System.out.println(largestNumber(new int[]{432,43243}));
        System.out.println(largestNumber(new int[]{999999991,9}));
    }
    private static String largestNumber(int[] nums) {
        int n = nums.length;
        String[] ns = new String[n];
        for (int i = 0; i < nums.length; i++) {
            ns[i] = Integer.toString(nums[i]);
        }
        Arrays.sort(ns, (o1, o2) -> {
            for (int i = 0; i < o1.length(); i++) {
                if (i >= o2.length()){
                   break;
                }
                if (o1.charAt(i) == o2.charAt(i))
                    continue;
                return o2.charAt(i) - o1.charAt(i);
            }
            String n1 = o1 + o2;
            String n2 = o2 + o1;
            for (int i = 0; i < n1.length(); i++) {
                if (n1.charAt(i) == n2.charAt(i))
                    continue;
                return n2.charAt(i) - n1.charAt(i);
            }
            return 1;
        });
        StringBuilder sb = new StringBuilder();
        for (String s : ns) {
            sb.append(s);
        }
        if (sb.charAt(0) == '0')
            return "0";
        return sb.toString();
    }
}
